<?php

namespace App\Http\Controllers\Shop\Business;

use App\Http\Controllers\ShopController;
use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Source as SourceModel;
use App\Models\Config as ConfigModel;
use App\Models\Region as RegionModel;
use Illuminate\Http\Request;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\Validator;

class BaseController extends ShopController
{
    public function register(Request $request)
    {
        $params = $request->only(['mobile','password']);

        $password = trim($params['password']);

        if(!$password)
        {
            return $this->error('密码不能为空');
        }
        
        $salt = build_randstr();

        $password = md5($password . $salt);

        // 封装数据
        $data = [
            'mobile' => $params['mobile'],
            'password' => $password,
            'salt' => $salt
        ];

        // 客户来源
        $source = SourceModel::where([['name','LIKE','%商城%']])->first();

        if($source)
        {
            $data['sourceid'] = $source['id'];
        }

        // 定义验证器
        $validate = [
            [
                'mobile' => ['required','unique:business','regex:/^1[356789]\d{9}$/'],
                'password' => ['required'],
                'salt' => ['required']
            ],
            [
                'mobile.required' => '手机号必填',
                'mobile.unique' => '手机号已注册',
                'mobile.regex' => '手机号格式错误',
                'password.required' => '密码必填',
                'salt.required' => '密码盐未知',
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        // 插入数据库
        $result = BusinessModel::create($data);

        if($result === false)
        {
            return $this->error('注册失败');
        }else{
            return $this->success('注册成功');
        }
    }

    public function login()
    {
        $mobile = request('mobile','');
        $password = trim(request('password',''));

        $business = BusinessModel::where(['mobile' => $mobile])->first();

        if(!$business)
        {
            return $this->error('手机号未注册');
        }

        $password = md5($password . $business['salt']);

        if($password != $business['password'])
        {
            return $this->error('密码错误');
        }

        // 建议直接调用Config模型查询
        $url = ConfigModel::where(['name' => 'url'])->value('value');

        $res = httpRequest($url . '/shop/business/avatar',['id' => $business['id']]);

        $avatarData = json_decode($res,true);

        $data = [
            'id' => $business['id'],
            'mobile' => $business['mobile'],
            'mobile_text' => $business['mobile_text'],
            'nickname' => $business['nickname'],
            'money' => $business['money'],
            'email' => $business['email'],
            'gender' => $business['gender'],
            'province' => $business['province'],
            'city' => $business['city'],
            'district' => $business['district'],
            'region_text' => $business['region_text'],
            'auth' => $business['auth'],
            'avatar' => $avatarData['data']['avatar']
        ];
;
        return $this->success('登录成功',$data);
    }

    public function check()
    {
        $id = request('id',0);
        $mobile = request('mobile','');

        // 组装条件一个数组
        $where = [
            'id' => $id,
            'mobile' => $mobile
        ];

        $business = BusinessModel::where($where)->first();

        if(!$business)
        {
            return $this->error('非法登录');
        }

        // 建议直接调用Config模型查询
        $url = ConfigModel::where(['name' => 'url'])->value('value');

        $res = httpRequest($url . '/shop/business/avatar',['id' => $business['id']]);

        $avatarData = json_decode($res,true);

        $data = [
            'id' => $business['id'],
            'mobile' => $business['mobile'],
            'mobile_text' => $business['mobile_text'],
            'nickname' => $business['nickname'],
            'money' => $business['money'],
            'email' => $business['email'],
            'gender' => $business['gender'],
            'province' => $business['province'],
            'city' => $business['city'],
            'district' => $business['district'],
            'region_text' => $business['region_text'],
            'auth' => $business['auth'],
            'avatar' => $avatarData['data']['avatar']?$avatarData['data']['avatar']:''
        ];

        return $this->success('验证成功',$data);
    }

    public function profile()
    {
        $params = request()->input();

        // dd($params);

        // 获取中间件传过来的参数
        $business = request()->get('business');

        // 组装数据
        $data = [
            'nickname' => trim($params['nickname']),
            'gender' => $params['gender']
        ];

        if($params['email'] != $business['email'])
        {
            $data['email'] = $params['email'];
            $data['auth'] = '0';
        }

        $password = $params['password'] ?? '';

        if(!empty($password))
        {
            $repass = md5($password . $business['salt']);

            if($repass === $business['password'])
            {
                return $this->error('新密码不能与原密码一致');
            }

            $salt = build_randstr();

            $data['password'] = md5($password . $salt);
            $data['salt'] = $salt;
        }

        // 地区
        // dd($params['code']);
        $path = RegionModel::where('code',$params['code'])->value('parentpath');

        if(!$path)
        {
            return $this->error('所选地区不存在');
        }

        [$province,$city,$district] = explode(',',$path);

        $data['province'] = $province ?? null;
        $data['city'] = $city ?? null;
        $data['district'] = $district ?? null;
        // return $business['avatar'];
        // dd($_FILES['avatar']);
        if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
        {
            $cdn = ConfigModel::where('name','url')->value('value');

            $url = $cdn . '/shop/business/upload';
            // return $url;
            // 第一个参数属于文件路径 第二个参数是文件类型 第三个是文件名

            $file =  new \CURLFile($_FILES['avatar']['tmp_name'],$_FILES['avatar']['type'],$_FILES['avatar']['name']);
            // dd($file);
            // return $_FILES['avatar'];
            // return 1;
            // var_dump($file);
            // return 1;
            // return $file;
            // return $business['id'];
            // return $business['avatar'];
            // return 1;
            $res = httpRequest($url,['avatar' => $file,'id' => $business['id']]);
            // var_dump($url);
            // return 1;
            // return $res;
            // dd($res);
            $avatar = json_decode($res,true);
            // return $avatar;
            if($avatar['code'] === 0)
            {
                return $this->error($avatar['msg']);
            }
            // return 1;
            // return $_FILES['avatar'];
            $data['avatar'] = $avatar['data'];
        }
        // return $data;
        $result = BusinessModel::where('id',$params['busid'])->update($data);
        // return 1;
        // return $result;
        // dd(1111);
        if($result !== false)
        {
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $cdn = ConfigModel::where('name','url')->value('value');

                $url = $cdn . '/shop/business/del';
                httpRequest($url,['id' => $business['id'],'avatar' => $business['avatar']]);
            }

            $business = BusinessModel::find($params['busid']);

            // 建议直接调用Config模型查询
            $url = ConfigModel::where(['name' => 'url'])->value('value');

            $res = httpRequest($url . '/shop/business/avatar',['id' => $business['id']]);
            // return $res;
            $avatarData = json_decode($res,true);

            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile'],
                'mobile_text' => $business['mobile_text'],
                'nickname' => $business['nickname'],
                'email' => $business['email'],
                'gender' => $business['gender'],
                'province' => $business['province'],
                'city' => $business['city'],
                'district' => $business['district'],
                'region_text' => $business['region_text'],
                'auth' => $business['auth'],
                'avatar' => $avatarData['data']['avatar']
            ];

            return $this->success('修改成功',$data);
        }else{
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $cdn = ConfigModel::where('name','url')->value('value');

                $url = $cdn . '/shop/business/del';
                httpRequest($url,['id' => $business['id'],'avatar' => $data['avatar']]);
            }
            return $this->error('修改失败');
        }
    }
}
